import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:webview_flutter/webview_flutter.dart';

import 'logic.dart';

class WebViewPage2 extends StatelessWidget {
  WebViewPage2({Key? key}) : super(key: key);

  final logic = Get.put(Logic());

  Future<bool> _onWillPop() async {
    if (await logic.canGoBack()) {
      print("回退事件");
      logic.goBack();
      return false; // 阻止默认的回退行为
    } else {
      return true; // 允许默认的回退行为
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: TextField(
          controller: logic.urlController,
          decoration: InputDecoration(
            hintText: 'Enter URL',
            border: InputBorder.none,
            suffixIcon: IconButton(
              icon: Icon(Icons.arrow_forward),
              onPressed: () {
                String url = logic.urlController.text;
                if (!url.startsWith('http')) {
                  url = 'https://$url'; // 自动添加 `https://` 前缀
                }
                logic.go(url); // 加载指定的 URL
              },
            ),
          ),
          style: TextStyle(color: Colors.white),
          onSubmitted: (value) {
            String url = value;
            if (!url.startsWith('http')) {
              url = 'https://$url';
            }
            logic.go(url); // 加载指定的 URL
          },
        ),
        backgroundColor: Colors.blue,
        actions: [
          IconButton(
            icon: Icon(Icons.arrow_back),
            onPressed: () {
              logic.goBack(); // 回退到上一个页面
            },
          ),
          IconButton(
            icon: Icon(Icons.refresh),
            onPressed: () {
              logic.reload(); // 重新加载当前页面
            },
          ),
        ],
      ),
      body: WebViewWidget(
        controller: logic.webViewController,
      ),
      // ),
    );
  }
}
